// 
// MessageButton.cs
// 
// Copyright © 2009 Jiří Zárevúcky <zarevucky.jiri@gmail.com>
//
// MessageButton.cs is part of SharpXMPP.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using Gtk;

using Galaxium.Core;
using Galaxium.Gui.GtkGui;

using L=Galaxium.Protocol.Xmpp.Library;
using Galaxium.Protocol.Xmpp.Library;
using Galaxium.Protocol.Xmpp.Library.Messaging;

namespace Galaxium.Protocol.Xmpp.GtkGui.Messages
{
	public class MessageButton: Button
	{
		private L.Client        _client;
		private MessageManager  _msgmanager;
		private Label           _label;

		private bool            _only_unread = true;

		public bool OnlyUnread {
			get { return _only_unread; }
			set {
				_only_unread = value;
				HandleMessageEvent (0);
			}
		}
		
		public MessageButton (L.Client client)
		{
			ThrowUtility.ThrowIfNull ("client", client);
			
			Relief = ReliefStyle.None;
			SetupButton ();

			_client = client;
			_msgmanager = client.MessageManager;
			_msgmanager.NewMessageEvent += HandleMessageEvent;
			_msgmanager.MessageStateChangedEvent += HandleMessageEvent;
			HandleMessageEvent (0);
		}

		private void SetupButton ()
		{
			_label = new Label ();
			var img = new Image (IconUtility.GetIcon ("message-unread"));
			var hbox = new HBox (false, 6);
			hbox.PackStart (img, false, true, 0);
			hbox.PackStart (_label, true, true, 0);
			Hide();
			hbox.ShowAll ();
			Add (hbox);
		}

		private void HandleMessageEvent (int id)
		{
			ThreadUtility.Dispatch (() => SetUnreadCount (_msgmanager.UnreadCount));
		}

		private void SetUnreadCount (int count)
		{
			string message;
			if (count == 0)
				message = "No unread messages";
			else if (count == 1)
				message = "<b>1 unread message</b>";
			else
				message = String.Format ("<b>{0} unread messages</b>", count);
			
			_label.Markup = message;
			
			if (_only_unread) {
				if (count == 0)
					Hide ();
				else
					Show ();
			}
		}

		public override void Destroy ()
		{
			_msgmanager.NewMessageEvent -= HandleMessageEvent;
			_msgmanager.MessageStateChangedEvent -= HandleMessageEvent;
			base.Destroy ();
		}

		protected override void OnClicked ()
		{
			new MessageListWindow (_client);
		}
	}
}
